package com.v1.video.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.iss.view.common.ToastAlone;
import com.v1.video.R;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.ResultInfo;
import com.v1.video.engine.NetEngine;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;

/***
 * 修改昵称的Activity
 * @author fengtao
 * 
 */
public class OptionModifyNickNameActivity extends BaseActivity{
		
	private static String TAG = "OptionModifyNickNameActivity";
	private EditText editTextNickName = null;
	private ImageView btnClear  = null;
	private TextView txtTitle = null;
//	private TextView txtNext = null;
	private Button btnConfirm = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_modify_nickname);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		editTextNickName = (EditText)findViewById(R.id.modify_edittext);
		btnClear = (ImageView)findViewById(R.id.modify_btn_clear);
		txtTitle = (TextView)findViewById(R.id.tv_title);
		btnConfirm = (Button)findViewById(R.id.btn_confirm);
//		txtNext = (TextView)findViewById(R.id.tv_right);
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		
		editTextNickName.setText(LoginInfo.getInstance().getNickName());
//		txtNext.setVisibility(View.VISIBLE);
//		txtNext.setText(R.string.phone_btn_save);
		txtTitle.setText(R.string.person_nickname_modify);
		if(LoginInfo.getInstance().getNickName() != null && LoginInfo.getInstance().getNickName().length() > 0){
			btnConfirm.setEnabled(true);
		}else{
			btnConfirm.setEnabled(false);
		}
	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		btnConfirm.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
//				new GetDataAsync().execute();
				Logger.i(TAG, "保存昵称");
				try{
					String nameStr = editTextNickName.getText().toString();
		            if (nameStr.equals("")) {
		                Toast.makeText(OptionModifyNickNameActivity.this, "昵称不能为空!", Toast.LENGTH_SHORT).show();
		                return;
		            } else {
		                byte name[] = nameStr.getBytes("GBK");
		                if (name != null) {
		                    /*if (name.length < 4 || name.length > 20) {
		                        Toast.makeText(OptionModifyNickNameActivity.this, "昵称格式错误", Toast.LENGTH_SHORT).show();
		                        return;
		                    }*/
		                	
		                	if(name.length < 4){
		                		Toast.makeText(OptionModifyNickNameActivity.this, "昵称太短,长度（4-20）个字！", Toast.LENGTH_SHORT).show();
		                		return;
		                	} else if( name.length > 20){
		                		Toast.makeText(OptionModifyNickNameActivity.this, "昵称太长,长度（4-20）个字！", Toast.LENGTH_SHORT).show();
		                		return;
		                	}
		                } else {
		                    Toast.makeText(OptionModifyNickNameActivity.this, "昵称格式错误", Toast.LENGTH_SHORT).show();
		                    return;
		                }
		            }
		            Pattern p1 = Pattern.compile("^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$");
		            Matcher m1 = p1.matcher(nameStr);
		            boolean b1 = m1.matches();
		            if (!b1) {
		                Toast.makeText(OptionModifyNickNameActivity.this, "昵称格式错误!", Toast.LENGTH_SHORT).show();
		                return;
		            }
		            new GetDataAsync(editTextNickName.getText().toString()).execute();
				}catch(Exception e){
					
				}
				
			}
		});
		findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
		btnClear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				editTextNickName.setText("");
			}
		});
		editTextNickName.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				int length = editTextNickName.getText().toString().length();
				if(length <= 0){
					btnConfirm.setEnabled(false);
				}else{
					btnConfirm.setEnabled(true);
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
    }
	
	/**
     * 检测版本
     */
    private class GetDataAsync extends AsyncTask<Void, Void, Boolean> {
        
        private String errorMsg = "";
        
        private ProgressDialog pd;
        String nickName = "";
        ResultInfo resultInfo = null;
        public GetDataAsync(String nickName) {                        
           this.nickName = nickName;
        }
        
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = Utils.getProgressDialog(OptionModifyNickNameActivity.this,getResources().getString(R.string.get_data), this);
            pd.show();
        }
        
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                NetEngine engine = new NetEngine();
                resultInfo = engine.nickNameModifyTo(nickName, LoginInfo.getInstance().getUserId());
            } catch (Exception e) {
                e.printStackTrace();
                errorMsg = e.getMessage();
            }
            return false;
            
        }
//        Uri uri = Uri.parse(versionInfo.url); 
//        Intent it   = new Intent(Intent.ACTION_VIEW,uri); 
//        startActivity(it);
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if(pd != null && pd.isShowing()){
                pd.cancel();
            }            
            if (errorMsg.equals("")) {
                if(resultInfo.getCode() == null || resultInfo.getCode().equals("")){
                	ToastAlone.showToast(OptionModifyNickNameActivity.this, "未知错误", 1);
                }else{
                	if(resultInfo.getCode().equals("1")){
                		//修改成功
                		Intent intent = new Intent();
	                    intent.putExtra("nickName", nickName);
	                    ToastAlone.showToast(OptionModifyNickNameActivity.this, resultInfo.getMessage(), 1);
	                    setResult(0, intent);
	                    OptionModifyNickNameActivity.this.finish();
                	}else{
                		ToastAlone.showToast(OptionModifyNickNameActivity.this, resultInfo.getMessage(), 1);
                	}
                }
                	
            } else {
                ToastAlone.showToast(OptionModifyNickNameActivity.this, errorMsg, 1);
            }
        }
    }
}
